package com.elderly.controller;

import com.elderly.model.Elder;
import com.elderly.model.result.RequestResult;
import com.elderly.model.result.ResultCode;
import com.elderly.service.IUserService;
import com.elderly.utils.PhoneUtils;
import com.elderly.utils.RedisUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description 用户相关行为控制接口
 * @Date 2021/10/6 15:02
 * @Created 30500
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 用户服务对象
     */
    @Resource
    private IUserService userServiceImpl;
    /**
     * redis 连接工具
     */
    @Resource
    private PhoneUtils phoneUtils;

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public RequestResult login(@RequestParam(name = "phone", required = true) String phone,
                               @RequestParam(name = "code", required = true) String code,
                               HttpServletRequest request) {
        // 判断是否处在手机号封禁状态
        if (phoneUtils.getPhone(phone, PhoneUtils.CHOOSE_PHONE_BAN) != null) return new RequestResult(ResultCode.RC_503, "暂时不能够获取验证码");
        // 尝试获取用户信息
        Elder elder = userServiceImpl.selectByPhone(phone);
        if (elder == null) {
            userServiceImpl.defaultUser(phone);
            elder = userServiceImpl.selectByPhone(phone);
        }
        // 获取保存的验证码信息进行比较验证
        String Ocode = phoneUtils.getCode(phone);
        if (Ocode == null) return new RequestResult(ResultCode.RC_503, "手机号未获取验证码");
        else if (!Ocode.equals(code)) {
            String count = phoneUtils.getPhone(phone, PhoneUtils.CHOOSE_PHONE_COUNT);
            if (count == null) phoneUtils.setPhone(phone, PhoneUtils.CHOOSE_PHONE_COUNT);
            else {
                phoneUtils.setPhone(phone, PhoneUtils.CHOOSE_PHONE_COUNT);
                int num = Integer.parseInt(count) + 1;
                if (num >= 5) {
                    phoneUtils.setPhone(phone, PhoneUtils.CHOOSE_PHONE_BAN);
                    phoneUtils.delPhone(phone);
                }
            }
            return new RequestResult(ResultCode.TC_403, "验证码错误");
        }
        // 信息校验全部通过, 删除登录计数
        if (phoneUtils.getPhone(phone, PhoneUtils.CHOOSE_PHONE_COUNT) != null)
            phoneUtils.delPhone(phone);
        return new RequestResult();
    }

}
